package com.dynabook.ebs.exception;

import com.dynabook.ebs.aop.LogInterceptor;
import com.dynabook.ebs.common.BaseResponse;
import com.dynabook.ebs.common.ErrorCode;
import com.dynabook.ebs.common.ResultUtils;
import com.dynabook.ebs.utils.LogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author GEK
 * @from GEK
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 捕获所有异常
    @ExceptionHandler(Exception.class)
    public BaseResponse<String> handleException(Exception e) {
        // 这里可以根据异常类型自定义返回内容
        LogUtils.error(LogUtils.getLogger(LogInterceptor.class),  "数据库: {}", e, e.getMessage());
        return ResultUtils.error(ErrorCode.DATA_ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        LogUtils.error(LogUtils.getLogger(LogInterceptor.class),  "BusinessException: {}", e, e.getMessage());
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        LogUtils.error(LogUtils.getLogger(LogInterceptor.class), "RuntimeException: {}", e, e.getMessage());
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
    }
}
